package com.victor.utils;

import com.alibaba.fastjson.JSON;
//import com.sp.platform.util.HttpUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by yangl on 15/2/3.
 */
public class SmsTest {
    private static Logger log = LoggerFactory.getLogger(SmsTest.class);

    /**
     * 创建测试
     */
    @Test
    public void templateCreateTest() {
        try {
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            map.put("cpid", 1234);
            map.put("name", "创建模板");
            map.put("sign", "测试");
            map.put("content", "你好，我是测试内容");

            //验证码类用下面的代码
//            map.put("content", "您的验证码是:${code},谢谢您的使用!");
            map.put("timestamp", new Date().getTime());

            //验证码类选填 应用下载地址或网站地址
//            map.put("url", "www.baidu.com");

            String _sign = createSign(map);
            System.out.println("sign:" + _sign);
            String sign = getKeyedDigestGBK(_sign, "**********");
            System.out.println(sign);

            //验证码类选填 应用下发验证码时的截图
//            map.put("img", readFileAsString("/Users/yanglei/Desktop/qq.png"));

            map.put("verify", sign);

            String resource = "http://api.hstang.net/service/template/create";

//            HttpClient httpClient = HttpUtils.getSecuredHttpClient();
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();

            String body = JSON.toJSONString(map);
            log.info(body);
            HttpPost post = new HttpPost(resource);
            StringEntity se = new StringEntity(body, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.addHeader("Content-Type", "application/json;charset=UTF-8");
            post.addHeader("accept", "application/json");
            post.setEntity(se);
            HttpResponse httpResponse = httpClient.execute(post);
            log.info(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
            log.info(IOUtils.toString(httpResponse.getEntity().getContent()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 文件转String
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String readFileAsString(String fileName) throws Exception {
        FileInputStream fis = new FileInputStream(fileName);
        BufferedInputStream in = new BufferedInputStream(fis);
        byte buffer[] = new byte[256];
        StringBuffer picStr = new StringBuffer();
        BASE64Encoder base64 = new BASE64Encoder();
        while (in.read(buffer) >= 0) {
            picStr.append(base64.encode(buffer));// 进行64位编码
        }
        fis.close();
        fis = null;
        in.close();
        in = null;
        buffer = null;
        return picStr.toString();
    }

    /**
     * 发送测试
     */
    @Test
    public void smsSendTest() {
        try {
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            map.put("cpid", 1234);
            map.put("templateId", "1234");
            map.put("mobile", "131****0491");
            //如果验证码类模板，放开此处代码
//            map.put("parameter", "{\"code\":\"123456\"}");
            map.put("timestamp", new Date().getTime());
			//扩展号码 选填 不清楚请赋空值
//			  map.put("spnumber", "37328");
			
            String _sign = createSign(map);
            System.out.println("sign:" + _sign);
            String sign = getKeyedDigestGBK(_sign, "**********");
            System.out.println(sign);
            map.put("verify", sign);

            String resource = "http://api.hstang.net/service/sms/send";

//            HttpClient httpClient = HttpUtils.getSecuredHttpClient();
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();

            String body = JSON.toJSONString(map);
            log.info(body);
            HttpPost post = new HttpPost(resource);
            StringEntity se = new StringEntity(body, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.addHeader("Content-Type", "application/json;charset=UTF-8");
            post.addHeader("accept", "application/json");
            post.setEntity(se);
            HttpResponse httpResponse = httpClient.execute(post);
            log.info(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
            log.info(IOUtils.toString(httpResponse.getEntity().getContent()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public String createSign(TreeMap<String, Object> tm) {
        StringBuffer buf = new StringBuffer();
        for (Map.Entry<String, Object> en : tm.entrySet()) {
            String name = en.getKey();
            String value = en.getValue().toString();
            if (value != null && value.length() > 0 && !"null".equals(value)) {
                buf.append(name).append('=').append(value).append('&');
            }
        }
        String _buf = buf.toString();
        return _buf.substring(0, _buf.length() - 1);
    }

    public String getKeyedDigestGBK(String strSrc, String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(strSrc.getBytes("GBK"));
            String result = "";
            byte[] temp;
            temp = md5.digest(key.getBytes("UTF8"));
            for (int i = 0; i < temp.length; i++) {
                result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
            }
            return result.toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
